package com.example.demo.score.handler.impl;

import com.example.demo.enumclass.NotificationProcessStatusEnum;
import com.example.demo.mq.bo.ScoreMqBo;
import com.example.demo.paymqnotification.entity.PayMqNotificationRecord;
import com.example.demo.paymqnotification.service.IPayMqNotificationRecordService;
import com.example.demo.score.handler.ScoreHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.time.LocalDateTime;
import java.util.Optional;

@AllArgsConstructor
@Slf4j
@Component
public class ScoreHandlerImpl implements ScoreHandler {

    private IPayMqNotificationRecordService iPayMqNotificationRecordService;

    private DataSourceTransactionManager dataSourceTransactionManager;
    private TransactionDefinition transactionDefinition;


    @Override
    public void handleScore(ScoreMqBo scoreMqBo) {
        Optional<PayMqNotificationRecord> payMqNotificationRecordOptional = iPayMqNotificationRecordService.lambdaQuery().eq(PayMqNotificationRecord::getOrderNo, scoreMqBo.getOrderNo()).oneOpt();
        if (!payMqNotificationRecordOptional.isPresent()) {
            throw new RuntimeException("通知记录不存在");
        }
        //TODO 判断是否处理过
        PayMqNotificationRecord payMqNotificationRecord = payMqNotificationRecordOptional.get();
        if (!payMqNotificationRecord.getStatus().equals(NotificationProcessStatusEnum.Padding.getStatus())) {
            throw new RuntimeException("已经处理过了");
        }
        //手动开启事务
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            dataSourceTransactionManager.commit(transactionStatus);
            //TODO 处理积分逻辑
            //修改状态
            payMqNotificationRecord.setStatus(NotificationProcessStatusEnum.Done.getStatus());
            payMqNotificationRecord.setUpdateTime(LocalDateTime.now());
            iPayMqNotificationRecordService.saveOrUpdate(payMqNotificationRecord);

        } catch (Exception ex) {
            log.error(".....处理积分逻辑异常,scoreMqBo={}", ex, scoreMqBo);
            dataSourceTransactionManager.rollback(transactionStatus);
        }


    }
}
